package com.qf.kady.ssm.controller;

import com.qf.kady.ssm.entity.ResultVO;
import com.qf.kady.ssm.pojo.User;
import com.qf.kady.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/4/21
 * \* Time: 11:50
 * \* 千峰JAVA2101班
 * \* Description: admin页面控制层
 * \
 */

@Controller
@RequestMapping("/admin")
public class AdminPageController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public ResultVO login(@RequestBody User user, HttpSession session){
        ResultVO vo = userService.login(user);
        session.setAttribute("logUserInfo",vo.isSuccess()?((User)(vo.getData())):null);
        return vo;
    }

    @GetMapping("/admin_main.html")
    public ModelAndView toAdminMain(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("admin/admin_main");
        return mav;
    }

    @GetMapping("/logout.html")
    public String logOut(HttpSession session){
        session.removeAttribute("logUserInfo");
        return "redirect:/admin/admin_main.html";
    }

    @GetMapping("/admin_header.html")
    public ModelAndView toAdminHeader(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("admin/admin_header");
        return mav;
    }

    @GetMapping("/admin_repasswd.html")
    public ModelAndView toChangePassword(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("admin/admin_repasswd");
        return mav;
    }

    @RequestMapping("/admin_repasswd_do")
    public ModelAndView changePassword(String userName,String oldPasswd, String newPasswd, String reNewPasswd, Model model){
        if(oldPasswd==newPasswd){
            model.addAttribute("error","新老密码不能相同！");
            model.addAttribute("oldPasswd",oldPasswd);
            model.addAttribute("newPasswd",newPasswd);
            return toChangePassword();
        }else{
            ResultVO resultVO = userService.changeWD(userName, oldPasswd, newPasswd);
            if(resultVO.isSuccess()){
                model.addAttribute("succ",resultVO.getMessage());
            }else{
                model.addAttribute("error",resultVO.getMessage());
                model.addAttribute("oldPasswd",oldPasswd);
                model.addAttribute("newPasswd",newPasswd);
            }
            return toChangePassword();
        }
    }

}
